/**
 * 碰撞检测系统
 */
import { System, World } from '../ecs';
import { Transform, Collider, Health, Bullet, GameState, EnemyAI } from '../components';
import { ParticleSystem } from './ParticleSystem';

export class CollisionSystem implements System {
  priority = 50;
  private particleSystem: ParticleSystem;

  constructor() {
    this.particleSystem = new ParticleSystem();
  }

  update(deltaTime: number, world: World): void {
    this.checkBulletCollisions(world);
    this.checkPlayerEnemyCollisions(world);
  }

  private checkBulletCollisions(world: World): void {
    const bullets = Array.from(world.entities).filter(e => 
      e.hasComponent('transform') && e.hasComponent('collider') && e.hasComponent('bullet')
    );
    
    const targets = Array.from(world.entities).filter(e => 
      e.hasComponent('transform') && e.hasComponent('collider') && e.hasComponent('health')
    );

    for (const bullet of bullets) {
      const bulletComponent = bullet.getComponent('bullet') as Bullet;
      const bulletTransform = bullet.getComponent('transform') as Transform;
      const bulletCollider = bullet.getComponent('collider') as Collider;

      for (const target of targets) {
        // 避免自己打自己
        if (bulletComponent.owner === 'player' && target.hasComponent('player')) continue;
        if (bulletComponent.owner === 'enemy' && target.hasComponent('enemyAI')) continue;

        const targetTransform = target.getComponent('transform') as Transform;
        const targetCollider = target.getComponent('collider') as Collider;

        if (this.checkCollision(bulletTransform, bulletCollider, targetTransform, targetCollider)) {
          this.handleBulletHit(world, bullet, target, bulletComponent);
          break; // 子弹击中后销毁
        }
      }
    }
  }

  private checkPlayerEnemyCollisions(world: World): void {
    const players = Array.from(world.entities).filter(e => 
      e.hasComponent('transform') && e.hasComponent('collider') && e.hasComponent('player')
    );
    
    const enemies = Array.from(world.entities).filter(e => 
      e.hasComponent('transform') && e.hasComponent('collider') && e.hasComponent('enemyAI')
    );

    for (const player of players) {
      const playerTransform = player.getComponent('transform') as Transform;
      const playerCollider = player.getComponent('collider') as Collider;

      for (const enemy of enemies) {
        const enemyTransform = enemy.getComponent('transform') as Transform;
        const enemyCollider = enemy.getComponent('collider') as Collider;

        if (this.checkCollision(playerTransform, playerCollider, enemyTransform, enemyCollider)) {
          this.handlePlayerEnemyCollision(world, player, enemy);
        }
      }
    }
  }

  private checkCollision(
    transformA: Transform, colliderA: Collider,
    transformB: Transform, colliderB: Collider
  ): boolean {
    const dx = transformA.x - transformB.x;
    const dy = transformA.y - transformB.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    const minDistance = colliderA.radius + colliderB.radius;

    return distance < minDistance;
  }

  private handleBulletHit(world: World, bullet: any, target: any, bulletComponent: Bullet): void {
    const bulletTransform = bullet.getComponent('transform') as Transform;
    const targetHealth = target.getComponent('health') as Health;
    const targetTransform = target.getComponent('transform') as Transform;

    // 造成伤害
    targetHealth.current -= bulletComponent.damage;

    // 创建击中效果
    this.particleSystem.createHitEffect(world, bulletTransform.x, bulletTransform.y, '#ffffff');

    // 销毁子弹
    world.removeEntity(bullet);

    // 如果目标死亡
    if (targetHealth.current <= 0) {
      this.handleEntityDestruction(world, target);
    }
  }

  private handlePlayerEnemyCollision(world: World, player: any, enemy: any): void {
    const playerHealth = player.getComponent('health') as Health;
    const enemyTransform = enemy.getComponent('transform') as Transform;
    const playerTransform = player.getComponent('transform') as Transform;

    // 玩家受到伤害
    playerHealth.current -= 50;

    // 创建碰撞爆炸效果
    this.particleSystem.createExplosion(world, playerTransform.x, playerTransform.y, '#ff6600', 12);

    // 销毁敌机
    world.removeEntity(enemy);

    // 检查玩家是否死亡
    if (playerHealth.current <= 0) {
      this.handlePlayerDeath(world, player);
    }
  }

  private handleEntityDestruction(world: World, entity: any): void {
    const transform = entity.getComponent('transform') as Transform;
    const gameState = this.getGameState(world);

    // 创建爆炸效果
    this.particleSystem.createExplosion(world, transform.x, transform.y, '#ffaa00', 10);

    // 如果是敌机，增加分数
    if (entity.hasComponent('enemyAI')) {
      const enemyAI = entity.getComponent('enemyAI') as EnemyAI;
      if (gameState) {
        switch (enemyAI.type) {
          case 'scout':
            gameState.score += 100;
            break;
          case 'destroyer':
            gameState.score += 300;
            break;
          case 'mothership':
            gameState.score += 1000;
            break;
        }
      }
    }

    // 销毁实体
    world.removeEntity(entity);
  }

  private handlePlayerDeath(world: World, player: any): void {
    const gameState = this.getGameState(world);
    const transform = player.getComponent('transform') as Transform;

    if (gameState) {
      gameState.lives--;
      
      if (gameState.lives <= 0) {
        // 游戏结束
        gameState.gameOver = true;
        console.log('💀 游戏结束！');
      } else {
        // 重生玩家
        const health = player.getComponent('health') as Health;
        health.current = health.max;
        
        // 重置位置
        const { width, height } = world.resources;
        transform.x = width / 2;
        transform.y = height - 100;
        transform.velocityX = 0;
        transform.velocityY = 0;
        
        console.log(`💔 玩家死亡！剩余生命: ${gameState.lives}`);
      }
    }
  }

  private getGameState(world: World): GameState | null {
    const entities = Array.from(world.entities).filter(e => e.hasComponent('gameState'));
    return entities.length > 0 ? entities[0].getComponent('gameState') as GameState || null : null;
  }
}